﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace LS.Dicom.Tools
{
    /// <summary>
    /// ImageViewer.xaml 的交互逻辑
    /// </summary>
    public partial class ImageViewer : UserControl
    {
        public static readonly DependencyProperty HasImageFileProperty = DependencyProperty.Register(nameof(HasImageFile), typeof(bool), typeof(ImageViewer));

        /// <summary>
        /// 是否已加载dicomFile
        /// </summary>
        public bool HasImageFile { get => (bool)this.GetValue(HasImageFileProperty); set => this.SetValue(HasImageFileProperty, value); }

        private List<string> imageFiles = new List<string>();
        public ImageViewer()
        {
            InitializeComponent();
        }

        private void OpenFile_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Multiselect = true;
            if (dialog.ShowDialog() == true)
            {
                imageFiles = dialog.FileNames.ToList();
                HasImageFile = false;
                imageViewer.LoadImageFile(imageFiles[0]);
                lb_Files.ItemsSource = imageFiles.Select(p => new { Name = Path.GetFileName(p), Path = p }).ToList();
                HasImageFile = true;
            }
        }

        private void lb_Files_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var rowData = lb_Files.SelectedValue as dynamic;
            var filePath = rowData.Path;
            HasImageFile = false;
            imageViewer.LoadImageFile(filePath);
            HasImageFile = true;
        }

        private void OnSaveDrawDataClick(Object sender, RoutedEventArgs e)
        {
            imageViewer.SaveDrawDataToFile();
        }

        private void OpenDrawDataClick(Object sender, RoutedEventArgs e)
        {
            var folder = Path.Combine(Environment.CurrentDirectory, "Draws");

            if (!Directory.Exists(folder))
                Directory.CreateDirectory("Draws");

            var dlg = new OpenFileDialog
            {
                Filter = "XML files (*.xml)|*.xml",
                DefaultExt = "xml",
                InitialDirectory = folder,
                RestoreDirectory = true
            };

            if (dlg.ShowDialog() == true)
            {
                imageViewer.LoadDrawDataFromFile(dlg.FileName);
            }
        }

        private void OnPrintClick(Object sender, RoutedEventArgs e)
        {
            imageViewer.Print();
        }

        private void OnSaveImageClick(Object sender, RoutedEventArgs e)
        {
            this.imageViewer.SaveBitmapToFile();
        }
    }
}
